#include "stdio.h"
#include "stdlib.h"
#include "FileReader.h"

#define BUFFER_LEN 256

void initFileReader(FileReader* self, char* fileName){
    self->fp = fopen(fileName, "rb");
    fread(self->szBuffer, BUFFER_LEN * sizeof(char), 1, self->fp);
    self->index = 0;
}

char readChar(FileReader* self){
    if (self->index < BUFFER_LEN)
        return self->szBuffer[self->index++];
    else {
        self->index = 0;
        fread(self->szBuffer, BUFFER_LEN*sizeof(char), 1, self->fp);
        return self->szBuffer[self->index++];
    }

}
int readInt(FileReader* self){
    int b1 = readChar(self) & 0xff;
    int b2 = readChar(self) & 0xff;
    int b3 = readChar(self) & 0xff;
    int b4 = readChar(self) & 0xff;
    return b4 << 24 | b3 << 16 | b2 << 8 | b1;
}

double readDouble(FileReader* this) {
    char chs[8];
    for (int i = 0; i < 8; i++) {
        chs[i] = readChar(this);
    }
    return *((double*)chs);
}

void unRead(FileReader* this){
    this->index--;
}
void close(FileReader* this){
    if (this->fp != NULL) {
        fclose(this->fp);
        this->fp = NULL;
    }
}

void destroyFileReader(FileReader* this) {
    free(this);
}
